package com.link4a.doms.web.controller;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.link4a.doms.exception.BusinessException;
import com.link4a.doms.model.User;
import com.link4a.doms.service.UserService;
import com.link4a.doms.web.ControllerSupport;
import com.link4a.doms.web.JsonResult;

@Controller
@RequestMapping(value="")
public class LoginController extends ControllerSupport {
	@Autowired
	private UserService userService;

	@RequestMapping(value="/login", method=RequestMethod.POST)
	@ResponseBody
	public JsonResult login(@RequestBody User userCondition) {
		try {
			userService.login(userCondition.getUsername(), userCondition.getPassword());
			return success();
		} catch (BusinessException e) {
			return fail(e.getMessage());
		}
	}

	@RequestMapping(value="/logout")
	public String logout(HttpSession session) {
		session.invalidate();
		return "redirect:/";
	}

	@RequestMapping(value="/login/sendMail/{username}")
	@ResponseBody
	public JsonResult sendMail(@PathVariable String username, HttpServletRequest request) {
		try {
			String url = StringUtils.substringBefore(request.getRequestURL().toString(), request.getServletPath());
			userService.sendResetMail(username, url);
			return success();
		} catch (BusinessException e) {
			return fail(e.getMessage());
		}
	}

	@RequestMapping(value="/login/reset/{username}/{applyCode}")
	public String reset(@PathVariable String username, @PathVariable String applyCode, HttpServletRequest request) {
		String errMessage = userService.validateApplyCode(username, applyCode);
		request.setAttribute("errMessage", errMessage);
		request.setAttribute("applyCode", applyCode);
		request.setAttribute("username", username);
		return "/reset";
	}

	@RequestMapping(value="/login/resetPassword", method=RequestMethod.POST)
	@ResponseBody
	public JsonResult resetPassword(@RequestParam String applyCode, @RequestParam String password) {
		userService.resetPassword(applyCode, password);
		return success();
	}
}
